using System;
using UnityEngine;

namespace Lean.Localization
{
	public class LeanLocalizationMultiLoader : MonoBehaviour
	{
		[Tooltip("The LeanLocalization target the translations will be loaded into. If this is empty, the first in the scene will automatically be used. If there are none in the scene, one will be created")]
		public LeanLocalization Target;

		[Tooltip("The file with all the translations in")]
		public TextAsset Source;

		[Tooltip("The string separating the phrase name from the language name")]
		public string Language = " : ";

		[Tooltip("The string separating the language name from the translation")]
		public string Separator = " = ";

		[Tooltip("The string denoting a new line within a translation")]
		public string NewLine = "\\n";

		[Tooltip("The string separating the translation from the comment (empty = no comments)")]
		public string Comment = " // ";

		private static readonly char[] newlineCharacters = new char[2]
		{
			'\r',
			'\n'
		};

		protected virtual void Start()
		{
			LoadFromSource();
		}

		[ContextMenu("Load From Source")]
		public void LoadFromSource()
		{
			if (!(Source != null))
			{
				return;
			}
			LeanLocalization leanLocalization = Target;
			if (leanLocalization == null && LeanLocalization.AllLocalizations.Count > 0)
			{
				leanLocalization = LeanLocalization.AllLocalizations[0];
			}
			if (leanLocalization == null)
			{
				leanLocalization = new GameObject("LeanLocalization").AddComponent<LeanLocalization>();
			}
			string[] array = Source.text.Split(newlineCharacters, StringSplitOptions.RemoveEmptyEntries);
			bool flag = false;
			foreach (string text in array)
			{
				int num = text.IndexOf(Separator);
				if (num == -1)
				{
					continue;
				}
				string text2 = text.Substring(0, num).Trim();
				int num2 = text2.IndexOf(Language);
				if (num2 == -1)
				{
					continue;
				}
				string phraseName = text2.Substring(0, num2).Trim();
				string text3 = text2.Substring(num2 + Language.Length).Trim();
				string text4 = text.Substring(num + Separator.Length).Trim();
				if (!string.IsNullOrEmpty(NewLine))
				{
					text4 = text4.Replace(NewLine, Environment.NewLine);
				}
				if (!string.IsNullOrEmpty(Comment))
				{
					int num3 = text4.LastIndexOf(Comment);
					if (num3 != -1)
					{
						text4 = text4.Substring(0, num3).Trim();
					}
				}
				LeanTranslation leanTranslation = leanLocalization.AddTranslation(text3, phraseName);
				leanTranslation.Text = text4;
				if (LeanLocalization.CurrentLanguage == text3)
				{
					flag = true;
				}
			}
			if (flag)
			{
				LeanLocalization.UpdateTranslations();
			}
		}
	}
}
